﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Ext.Net;
using Kwan.Data;
using ZP.Data;
using ZP.Service;

namespace ZP.Web.Admin.Role
{
    public partial class Default : UIPage
    {
        protected static IList<TModule> ModuleList = null;
        IList<VRoleModule> RoleModuleList = new List<VRoleModule>();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                ModuleList = new Expression().List<TModule>();
                BtnAddInfo.Hidden = !permit[0];
                BtnDelRole.Hidden = !permit[3];
                BtnChangeEnable.Hidden = !permit[2];
                
                if (permit[3])
                {
                    List<GridCommand> gridCommand = new List<GridCommand>{
                        ExtHelper.CreateGridCommand("Delete", Icon.Delete, "删除", "删除该条记录")
                    };
                    GridPanel1.ColumnModel.Columns.Add(ExtHelper.CreateCommandColumn(gridCommand));
                }
            }
        }

        protected void BtnAddInfo_Click(object sender, EventArgs e)
        {
            SetEditWindow(new TRole());
            EditWindow.Show();
        }

        [DirectMethod]
        public void DeleteSelected(string obj)
        {
            CrudManage.DeleteSelected(obj, "ZP_Role");
            Store1.DataBind();
        }

        [DirectMethod]
        public void EditInfo(string id)
        {
            if (!permit[2]) return;
            SetEditWindow((TRole.entityID == id).ListFirst<TRole>());
            EditWindow.Show();
        }

        protected void RefreshDS(object sender, StoreRefreshDataEventArgs e)
        {
            NameValueCollection ps = new NameValueCollection();
            ps.Set("gridsort", e.Sort);
            ps.Set("dir", e.Dir.ToString());

            int pageindex = e.Start / e.Limit;
            Kwan.Data.Region r = new Kwan.Data.Region(pageindex, e.Limit);
            IList<TRole> ListView = new Expression().List<TRole>(r);

            e.Total = new Expression().Count<TRole>();

            Store1.DataSource = ListView;
            Store1.DataBind();
        }

        protected void SetEditWindow(TRole tt)
        {
            txtID.Text = tt.EntityID.ToString();
			txtNameCN.Text = tt.NameCN;
			txtNameEN.Text = tt.NameEN;
            txtMemo.Text = tt.Memo;
            txtEnable_False.Checked = !tt.Enable;
            txtEnable_True.Checked = tt.Enable;
        }

        protected void SaveEditWindow(object sender, DirectEventArgs e)
        {
            TRole tt = string.IsNullOrEmpty(txtID.Text) ? new TRole() :
                (TRole.entityID == int.Parse(txtID.Text)).ListFirst<TRole>();

            tt.NameCN = txtNameCN.Text;
            tt.NameEN = txtNameEN.Text;
            tt.Enable = txtEnable_True.Checked;
            tt.Memo = txtMemo.Text;

            DBContext.Save(tt);

            Store1.DataBind();
            EditWindow.Hide();
        }

        [DirectMethod]
        public void ChangeState(string obj, string NameValue)
        {
            IList<TRole> list = JSON.Deserialize<IList<TRole>>(obj);
            if (list.Count > 0)
            {
                CrudManage.ChangeState(list, NameValue);
                Store1.DataBind();
            }
            else
            {
                ExtHelper.GetNotification("系统提示", "请至少选择一项！").Show();
            }
        }

        [DirectMethod]
        public void AfterEditRM(object customer)
        {
            TRoleModule c = JSON.Deserialize<TRoleModule>(customer.ToString());

            DBContext.Save(c);
            PermitDS.CommitChanges();
        }

        //[DirectMethod]
        //public void SetModule(string roleRecord, string roleModuleRecord, string ModuleID)
        //{
        //    string[] modules = ModuleID.Split(',');
        //    List<TRoleModule> roleModuleList = JSON.Deserialize<List<TRoleModule>>(roleModuleRecord);
        //    List<TRole> roleList = JSON.Deserialize<List<TRole>>(roleRecord);
        //    if (roleList.Count == 0) return;
        //    string roleID = roleList[0].id;
        //    foreach (string mid in modules)
        //    {
        //        int moduleID = Convert.ToInt32(mid);
        //        List<TRoleModule> child = roleModuleList.FindAll(delegate(TRoleModule tt) { return tt.ModuleID == moduleID && tt.RoleID == roleID; });
        //        if (child.Count == 0)
        //        {
        //            TRoleModule t = new TRoleModule();
        //            t.ModuleID = moduleID; t.Permit = "4"; t.RoleID = roleID;
        //            bsRoleModule.EntityDAO.Save(t);
        //        }
        //    }
        //    GetRoleModule(roleID.ToString());
        //}

        [DirectMethod]
        public void GetRoleModule(string id)
        {


            IList<VRoleModule> RoleModuleList = (VRoleModule.roleID == id).List<VRoleModule>();
            PermitDS.DataSource = RoleModuleList;
            PermitDS.DataBind();

        }

        [DirectMethod]
        public string GetModule(string id)
        {
            ModuleTree.Disabled = false;
            RoleModuleGP.Disabled = true;
            RoleModuleList = (VRoleModule.roleID == id).List<VRoleModule>();
            IList<TModule> list = new Expression().List<TModule>();
            IList<TModule> Parent = list.AsQueryable().Where(c => c.Pid == 0).ToList();
            string json = CreateModuleTree(list, Parent, false).ToJson();
            return json;
        }

        [DirectMethod]
        public string NodeLoad(string nodeID)
        {
            string json = string.Empty;
            if (nodeID == "root")
            {
                IList<TModule> list = new Expression().List<TModule>();
                IList<TModule> Parent = list.AsQueryable().Where(c => c.Pid == 0).ToList();
                json = CreateModuleTree(list, Parent, true).ToJson();
            }
            return json;
        }

        private TreeNodeCollection CreateModuleTree(IList<TModule> list, IList<TModule> Parent,bool IsFirst)
        {
            TreeNodeCollection nodes = new TreeNodeCollection(false);

            foreach (TModule t in Parent)
            {
                TreeNode node = new TreeNode();
                List<TModule> child = list.AsQueryable().Where(c => c.Pid == t.EntityID).ToList();
                if (child.Count > 0)
                {
                    node.NodeID = t.EntityID.ToString();
                    node.Text = t.NameCN;
                    //node.SingleClickExpand = true;
                    node.Expanded = true;
                    if (t.Pid > 0) node.Checked = ThreeStateBool.True;
                    node.Nodes.AddRange(CreateModuleTree(list, child, IsFirst));
                    //node.Nodes.Add();
                }
                else
                {
                    //RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
                    //int rowindex = sm.SelectedRows[0].RowIndex;
                    node.Leaf = true;
                    node.NodeID = t.EntityID.ToString();
                    node.Text = t.NameCN;
                    bool NodeChecked = false;
                    if (RoleModuleList.Count > 0)
                    {
                        NodeChecked = RoleModuleList.AsQueryable().Where(c => c.ModuleNameEN.Equals(t.NameEN)).Count() > 0;
                    }
                    node.Checked = NodeChecked ? ThreeStateBool.True : ThreeStateBool.False;
                    //string iconFile = "/Ext/resources/images/Icons/" + t.NameEN + ".png";
                    //if (File.Exists(HttpContext.Current.Server.MapPath(iconFile)))
                    //    node.IconFile = iconFile;
                    //node.SingleClickExpand = true;
                    node.IconCls = "Kwan-icon-" + t.NameEN;
                }
                //root.Loader.Add(node);
                //ModuleTree.Root.Add(node);
                nodes.Add(node);
            }
            return nodes;
        }

        [DirectMethod]
        public void ChangeChecked(int moduleID, bool IsChecked)
        {
            RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
            foreach (SelectedRow row in sm.SelectedRows)
            {
                if (IsChecked)
                {
                    TRoleModule rm = new TRoleModule();
                    rm.ModuleID = moduleID;
                    rm.RoleID = row.RecordID;
                    rm.Permit = "00000";
                    DBContext.Save(rm);
                }
                else
                {
                    (TRoleModule.moduleID == moduleID & TRoleModule.roleID == row.RecordID).Delete<TRoleModule>();
                }
            }
        }


        [DirectMethod]
        public int[] LoadPermit(int moduleID)
        {
            RoleModuleGP.Disabled = false;
            RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
            List<int> r=new List<int>();
            //int[] r = new int[] { };
            if (sm.SelectedRows.Count > 0)
            {

                IList<TRoleModule> rmList = (TRoleModule.moduleID == moduleID & TRoleModule.roleID == sm.SelectedRows[0].RecordID).List<TRoleModule>();
                bool[] permit = new bool[] { false, false, false, false, false };
                if (rmList.Count > 0)
                {
                    permit = UserUtil.BoolPermit(rmList[0].Permit);
                }
                List<object> list = new List<object>();
                list.Add(new { Value = permit[0], Text = "创建" });
                list.Add(new { Value = permit[1], Text = "读取" });
                list.Add(new { Value = permit[2], Text = "更新" });
                list.Add(new { Value = permit[3], Text = "删除" });
                list.Add(new { Value = permit[4], Text = "审核" });

                this.PermitDS.DataSource = list;
                this.PermitDS.DataBind();

                for (int i = 0; i < permit.Length; ++i)
                {
                    if (permit[i])
                        r.Add(i);
                }
                //r = r.Substring(0, r.Length - 1);
            }
            return r.ToArray();
        }

        [DirectMethod]
        public void ChangePermit(int rowIndex, string val, string moduleID)
        {
            RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;

            TRoleModule t = (TRoleModule.moduleID == moduleID & TRoleModule.roleID == sm.SelectedRows[0].RecordID).ListFirst<TRoleModule>();
            if (t !=null)
            {
                t.Permit = t.Permit.Remove(rowIndex, 1).Insert(rowIndex, val);
                DBContext.Save(t);
            }
        }
        
    }
}